from . import admin
from app import db
from app.schemas import UserOutSchema
from app.models import User
from flask import render_template, request
from app.some_func import wapper, fail_api, success_api, table_api
from werkzeug.security import generate_password_hash
# 用户管理
@admin.get('/user')
@wapper
def user_main():
    return render_template('admin/user/main.html')
# 用户分页查询
@admin.get('/user/data')
@wapper
def user_data():
    # 获取请求参数
    real_name = request.args.get('realname')
    username = request.args.get('username')
    filters = []
    if real_name:
        filters.append(User.realname.contains(real_name))
    if username:
        filters.append(User.username.contains(username))
    users = User.query.filter(*filters).order_by(User.id.desc()).paginate(page=request.args.get('page', type=int),per_page=request.args.get('limit', type=int),error_out=False)
    return table_api(data=UserOutSchema(many=True).dump(users), count=users.total)
# 用户增加
@admin.get('/user/add')
@wapper
def user_add():
    return render_template('admin/user/add.html')
@admin.post('/user/save')
@wapper
def user_save():
    username = request.json.get('username')
    realname = request.json.get('realname')
    password = request.json.get('password')
    if not username or not realname or not password:
        return fail_api(msg="所有内容不得为空")
    if bool(User.query.filter_by(username=username).count()):
        return fail_api(msg="用户已经存在")
    user = User(username=username, realname=realname,password_hash=generate_password_hash(password))
    db.session.add(user)
    db.session.commit()
    return success_api(msg="增加成功")
# 删除用户
@admin.delete('/user/remove/<int:id>')
@wapper
def user_delete(id):
    user = User.query.filter_by(id=id).first()
    res = User.query.filter_by(id=id).delete()
    db.session.commit()
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")
# 编辑用户
@admin.get('/user/edit/<int:id>')
@wapper
def user_edit(id):
    user = User.query.filter_by(id=id).first()
    return render_template('admin/user/edit.html', user=user)
# 编辑用户
@admin.put('/user/update')
@wapper
def user_update():
    if not request.json.get('username') or not request.json.get('realname') or not request.json.get('password'):
        return fail_api(msg="所有内容不得为空")
    id = request.json.get("userId")
    username = request.json.get('username')
    realname = request.json.get('realname')
    password_hash=generate_password_hash(request.json.get('password'))
    User.query.filter_by(id=id).update({'username':username, 'realname':realname, 'password_hash':password_hash})
    db.session.commit()
    return success_api(msg="更新成功")